package com.tjhk.lock.cas;

import java.util.concurrent.atomic.AtomicInteger;

public class FairLock {

    /**
     * 当前锁的记录号
     */
    private AtomicInteger serviceNum =  new AtomicInteger(0);

    /**
     * 发放锁号码
     */
    private AtomicInteger tickNum =  new AtomicInteger(0);

    /**
     * 存储线程的获取排队的号码
     */
    private static ThreadLocal<Integer> threadLocalNums = new ThreadLocal<>();

    /**
     * 锁重入次数
     */
    private static volatile int count = 0;

    public void lock(){
        Integer currentNum = threadLocalNums.get();
        if ( currentNum!=null && currentNum == serviceNum.get()){
            count++;
//            System.out.println(current.getName()+"进入锁,count:"+count);
            return;
        }
        // 获取排队号码
        currentNum = getTicket();
        threadLocalNums.set(currentNum);
        while (currentNum != serviceNum.get());
    }

    public void unlock(){
        Integer currentNum = threadLocalNums.get();
        if ( currentNum!=null && currentNum == serviceNum.get()){
            if (count > 0){
                count--;
            }else {
                threadLocalNums.remove();
                serviceNum.set(currentNum + 1);
            }
//            System.out.println(current.getName()+"进入锁,count:"+count);
        }
    }

    Integer getTicket(){
        return tickNum.getAndIncrement();
    }
}
